﻿using System.Net.Mail;

namespace VIT.BusinessLogicLayer
{
    using System;
    using System.Linq;

    using VIT.DataAccessLayer;
    using VIT.Entity;
    using VIT.Library;
    using VIT.DataTransferObjects;

    public class UserBLL : BLLBase
    {
        private readonly IUserInfoDAL _userInfoDAL;
        private readonly IUserAccountDAL _userAccountDAL;
        private readonly IUserMemberDAL _userMemberDAL;
        private readonly IUserAdminDAL _userAdminDAL;

        #region Constructor

        public UserBLL(string connectionString = "")
            : base(connectionString)
        {
            this._userInfoDAL = new UserInfoDAL(this.DatabaseFactory);
            this._userAccountDAL = new UserAccountDAL(this.DatabaseFactory);
            this._userMemberDAL = new UserMemberDAL(this.DatabaseFactory);
            this._userAdminDAL = new UserAdminDAL(this.DatabaseFactory);
        }

        #endregion

        #region Internal
        public UserInfoDto GetProfileByUserName(int id, int companyId)
        {
            var query = this._userInfoDAL.GetAll()
                .Where(info => info.id == id && info.CompanyId == companyId)
                .Select(info => new UserInfoDto
                    {
                        Address = info.Address,
                        Birthday = info.Birthday,
                        CreateDate = info.CreateDate,
                        Email = info.Email,
                        FullName = info.FullName,
                        Mobile = info.Mobile,
                        Id = info.id
                    });

            var data = query.FirstOrDefault();

            return data;
        }

        public UserInfoDto GetProfileByUserName(string userName, int companyId)
        {
            var query = this._userInfoDAL.GetAll()
                .Where(info => info.UserAccount.UserName == userName && info.CompanyId == companyId)
                .Select(info => new UserInfoDto
                {
                    Address = info.Address,
                    Birthday = info.Birthday,
                    CreateDate = info.CreateDate,
                    Email = info.Email,
                    FullName = info.FullName,
                    Mobile = info.Mobile,
                    Id = info.id
                });

            var data = query.FirstOrDefault();

            return data;
        }
        #endregion

        #region Method

        //public UserInfo InsertUserInfo(UserInfo userInfo)
        //{
        //    this._userInfoDAL.Add(userInfo);
        //    this.SaveChanges();
        //    return userInfo;
        //}

        public UserInfoDto GetProfile(int userId, int companyId)
        {
            var query = this._userInfoDAL.GetAll().Where(e => e.id == userId && e.CompanyId == companyId)// && e.CompanyId == companyId);
            .Select(e => new UserInfoDto
            {
                CreateDate = e.CreateDate,
                Birthday = e.Birthday,
                Address = e.Address,
                FullName = e.FullName,
                Mobile = e.Mobile,
                Email = e.Email
            });

            var data = query.FirstOrDefault();

            return data;
        }

        public bool KiemTraUser(string UserName, int companyId)
        {
            if (this.GetProfileByUserName(UserName, companyId) != null)
            {
                throw new BusinessLogicLayerException("Account không tồn tại");
            }
            return false;
        }

        public bool QuenPass(string UserName, string passwordnew)
        {
            var mem = this._userAccountDAL.Get(o => o.UserName == UserName);
            bool kt = false;
            if (mem != null)
            {
                mem.Password = passwordnew.EnCodeMD5();
                this._userAccountDAL.Update(mem);
                try
                {
                    this.SaveChanges();
                    kt = true;
                }
                catch (Exception)
                {
                    kt = false;
                    // throw new System.Configuration.Provider.ProviderException(ex.Message);
                }
            }
            return kt;
        }
        //public string SendMail(string toList, string from, string ccList, string subject, string body)
        //{

        //    MailMessage message = new MailMessage();
        //    SmtpClient smtpClient = new SmtpClient();
        //    string msg = string.Empty;
        //    try
        //    {
        //        MailAddress fromAddress = new MailAddress(from);
        //        message.From = fromAddress;
        //        message.To.Add(toList);
        //        if (ccList != null && ccList != string.Empty)
        //            message.CC.Add(ccList);
        //        message.Subject = subject;
        //        message.IsBodyHtml = true;
        //        message.Body = body;
        //        smtpClient.Host = "smtp.gmail.com";   // We use gmail as our smtp client
        //        smtpClient.Port = 587;
        //        smtpClient.EnableSsl = true;
        //        smtpClient.UseDefaultCredentials = true;
        //        smtpClient.Credentials = new System.Net.NetworkCredential("Your Gmail User Name", "Your Gmail Password");

        //        smtpClient.Send(message);
        //        msg = "Successful<BR>";
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = ex.Message;
        //    }
        //    return msg;
        //}
        public void Send_Email(string host, bool enableSSL, string SendFrom, string SendTo, string Password, int port, string Subject, string Body)
        {
            try
            {
                MailManager mail = new MailManager();
                mail.EnableSSL = enableSSL;
                mail.Host = host;
                mail.Port = port;
                mail.From = SendFrom;
                mail.Password = Password;
                mail.To = SendTo;
                mail.Title = Subject;
                mail.Content = Body;
                mail.SendEmail();
            }
            catch (Exception ex)
            {
                throw new BusinessLogicLayerException("Lỗi Email: " + ex.Message);
            }
        }

        public void UpDateChangePass(UserInfoDto dto, bool enterOldPass, int companyId)
        {
            //var user = this._userInfoDAL.GetById(dto.Id);
            var acc = this._userAccountDAL.GetById(dto.Id);
            if (acc == null)
                throw new BusinessLogicLayerException("Account không tồn tại");
            var newPass = dto.PassOld.EnCodeMD5();
            if (enterOldPass && acc.Password == newPass)
            {
                if (dto.PassNew == dto.PassConfirm)
                {
                    acc.Password = newPass;
                    this._userAccountDAL.Update(acc);
                }
                else
                    throw new BusinessLogicLayerException("Mật khẩu xác nhận không đúng");
            }
            else
                throw new BusinessLogicLayerException("Mật khẩu không đúng");

            try
            {
                this.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new System.Configuration.Provider.ProviderException(ex.Message);
            }

        }

        public void UpdateProfile(UserInfoDto dto, bool enterOldPass, int companyId)
        {
            var user = this._userInfoDAL.GetById(dto.Id);
            if (user != null)
            {
                user.Birthday = dto.Birthday;
                user.Address = dto.Address;
                user.FullName = dto.FullName;
                user.Mobile = dto.Mobile;
                user.Email = dto.Email;
                this._userInfoDAL.Update(user);
                var acc = this._userAccountDAL.GetById(dto.Id);
                if (acc == null)
                    throw new BusinessLogicLayerException("Account không tồn tại");
                var PassOld = dto.PassOld.EnCodeMD5();
                if (enterOldPass == false && acc.Password == PassOld)
                {
                    if (dto.PassNew == dto.PassConfirm)
                    {
                        acc.Password = dto.PassNew.EnCodeMD5();
                        this._userAccountDAL.Update(acc);
                    }
                    else
                        throw new BusinessLogicLayerException("Mật khẩu xác nhận không đúng");
                }
                else
                    throw new BusinessLogicLayerException("Mật khẩu không đúng");
                try
                {
                    this.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new System.Configuration.Provider.ProviderException(ex.Message);
                }
            }
        }

        public void InsertProfile(UserInfoDto dto, int companyId)
        {
            if (dto.PassNew != dto.PassConfirm)
            {
                throw new BusinessLogicLayerException("Mật khẩu xác nhận không đúng");
            }
            var userInfo = new UserInfo();
            userInfo.Birthday = dto.Birthday;
            userInfo.Address = dto.Address;
            userInfo.FullName = dto.FullName;
            userInfo.Mobile = dto.Mobile;
            userInfo.Email = dto.Email;
            userInfo.CompanyId = companyId;
            userInfo.CreateDate = DateTime.Now;

            userInfo.UserAccount = new UserAccount();
            userInfo.UserAccount.UserName = dto.UserName;
            userInfo.UserAccount.Password = dto.PassNew.EnCodeMD5();

            userInfo.UserMember = new UserMember();
            userInfo.UserMember.ActiveCode = dto.UserName.EnCodeMD5();

            this._userInfoDAL.Add(userInfo);

            try
            {
                this.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new System.Configuration.Provider.ProviderException(ex.Message);
            }
        }



        #endregion
    }
}



